import {
  successResponseType,
  failRejectType,
  successDataType,
  failDataType
} from "CustomTypes";
import { isEqual, isUndefined } from "lodash";
import { checkAccessTokenMsg } from "./token";

/**
 *http请求的方式
 *
 * @export
 * @enum {number}
 */
export enum reqMethod {
  get = "get",
  post = "post",
  put = "put",
  delete = "delete"
}

/**
 * http响应的成功、失败状态码。
 */
enum responseStatus {
  success = 200,
  fail = 401
}

/**
 * 提取http中的数据。
 * 可以返回成功的，也可以返回失败的。
 *
 * 如果返回的数据中有token过期的信息，就返回登录页面。
 * 这里的返回必须使用any，否则报错。
 */
export const getReqDataNew = (
  tempResult: successResponseType | failRejectType
): any => {
  const {
    result: { status, data }
  } = tempResult;
  const flagToken = checkAccessTokenMsg(data as failDataType);
  if (!flagToken) return;

  return { flag: isEqual(status, responseStatus.success), data };
};

class SuccessResponse implements successResponseType {
  requestId: string;
  result: { status: number; data: { status: number; data: object } };
  constructor() {
    this.requestId = "";
    this.result = {
      status: 0,
      data: { status: 200, data: { status: responseStatus.success, data: {} } }
    };
  }
}

/**
 * 如果http请求成功，生成一个自定义的数据体
 */
export const initSuccessResponseData = () => new SuccessResponse();

class FailReject implements failRejectType {
  requestId: string;
  result: {
    status: number;
    data: { status: number; msg: string; error: object };
  };

  constructor(status: number, msg = "", error = {}) {
    this.requestId = "";
    this.result = {
      status: 0,
      data: { status, msg, error }
    };
  }
}

/**
 * 如果http请求失败，生成一个自定义的数据体
 */
export const initFailRejectData = (
  msg: string,
  status?: number,
  error?: object
) => new FailReject(isUndefined(status) ? 1 : status, msg, error);

/**
 *  判断当前http返回的状态是否成功
 */
export const isSuccess = (data: number): boolean =>
  isEqual(data, responseStatus.success);

/**
 *  判断当前http返回的状态是否失败
 */
export const isFailed = (data: number): boolean =>
  isEqual(data, responseStatus.success);
